package com.umbrella.worker.web.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.umbrella.worker.dto.ContactDO;
import com.umbrella.worker.dto.NeedDO;
import com.umbrella.worker.dto.OrderDO;
import com.umbrella.worker.dto.OrderDetailDO;
import com.umbrella.worker.dto.SupplierDO;
import com.umbrella.worker.query.ContactQuery;
import com.umbrella.worker.query.NeedQuery;
import com.umbrella.worker.query.SupplierQuery;
import com.umbrella.worker.result.JsonResultDO;
import com.umbrella.worker.result.JsonResultSupport;
import com.umbrella.worker.result.ResultDO;
import com.umbrella.worker.result.ResultSupport;
import com.umbrella.worker.service.IContactService;
import com.umbrella.worker.service.IMemberService;
import com.umbrella.worker.service.INeedService;
import com.umbrella.worker.service.IOrderService;
import com.umbrella.worker.service.ISuppliersService;
import com.umbrella.worker.util.PageBeanUtil;

@Controller
@RequestMapping(value = "/need")
public class NeedController extends BaseController{
	@Autowired
	private INeedService needService;

	@Autowired
	private ISuppliersService suppliersService;
	
	@Autowired
	private IContactService contactService;
	
	@RequestMapping(value = "/create.html", method = RequestMethod.POST)
	public ModelAndView create(ModelAndView mav, 
			NeedDO needDO,
			HttpServletRequest request) {
	
		Cookie cookie = getCookieByName(request, "MEMBER_ID");
		
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		}
		
		Integer memberId = Integer.parseInt(cookie.getValue());
		cookie = getCookieByName(request, "MEMBER_MOBILE");
		String memberMobile = cookie.getValue();
		ContactQuery contactQuery = new ContactQuery();
		contactQuery.setIsDefault(1);
		contactQuery.setMemberId(memberId);
		ResultDO resultDO = contactService.list(contactQuery);
		
		ContactDO contactDO = null;
		if(resultDO.isSuccess()) {
			List<ContactDO> list = (List<ContactDO>) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			contactDO = list.get(0);
		} else {
			return new ModelAndView("redirect:/members/contacts.html");
		}
		
		needDO.setwContact(contactDO.getwCContact());
		needDO.setwAddress(contactDO.getwCAddress());
		needDO.setwMemberId(memberId);
		needDO.setwMemberMobile(contactDO.getwCTelephone());
		needDO.setCreateAuthor(memberMobile);
		resultDO = needService.create(needDO);
		System.out.println(resultDO.isSuccess());
		if(resultDO.isSuccess()) {
			mav.setViewName("success");
		} else {
			mav.setViewName("error");
		}
		
		return mav;
	}
	
	
	@RequestMapping(value = "/getNeed/{id}.html", method = RequestMethod.GET)
	public ModelAndView getNeed(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		
		Cookie cookie = getCookieByName(request, "MEMBER_ID");
		
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		}
		
		ResultDO result = needService.get(id);
		
		if(result.isSuccess()) {
			mav.setViewName("need/detail");
			mav.addObject("NEED_INFO", result.getModel(ResultSupport.FIRST_MODEL_KEY));
		} else {
			mav.setViewName("error");
		}
		return mav;
	}
	
	@RequestMapping(value = "/confirmNeed/{id}.json", method = RequestMethod.GET)
	public ModelAndView confirmNeed(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		JsonResultDO jsonResultDO = new JsonResultSupport();
		Integer supplierId = (Integer) request.getSession().getAttribute("MANAGER_SUPPLIER_ID");
		
		if(supplierId == null) {
			return new ModelAndView("redirect:/manager/login.html");
		}
		ResultDO sresultDO=suppliersService.get(supplierId);
		SupplierDO supplierDO=(SupplierDO) sresultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
		
		//判断渠道商是否可以接单，限制5条，未处理的需求单
		if(supplierId!=null){
			NeedQuery query = new NeedQuery();
			query.setStatus(2);//已抢单状态
			query.setSupplierId(supplierId);
			ResultDO list2 = needService.list(query);
			if(list2.isSuccess()) {
				List<NeedDO> counts= (List<NeedDO>) list2.getModel(ResultSupport.FIRST_MODEL_KEY);
				if(counts!=null && counts.size()>=5){
					jsonResultDO.setInfo("您还有需求单未处理，不能继续抢单！");
					jsonResultDO.setStatus("0");
					mav.addObject("JSON_DATA", jsonResultDO);
					return mav;
				}
			}
		}
		
		NeedDO need=new NeedDO();
		ResultDO resultDO=needService.get(id);
		need = (NeedDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
		int wsMoney=supplierDO.getwSMoney().intValue();
		
		//获取需要支付的黑币
		int wMoney=0;
		String hei=request.getParameter("heibi");
		if(hei!=null && !("".equals(hei))){
			wMoney=Integer.parseInt(hei);
		}
		
		if(wsMoney>=wMoney){	
			int sMoney=wsMoney-wMoney;
			Integer sMoneyI=new Integer(sMoney);
			supplierDO.setwSMoney(sMoneyI);
			ResultDO resultSDO=suppliersService.modifi(supplierDO);
			if(resultSDO.isSuccess()) {
				jsonResultDO.setInfo("嘿币扣除成功");
				jsonResultDO.setStatus(JsonResultDO.JSON_SUCCESS);
				mav.addObject("JSON_DATA", jsonResultDO);
			} else {
				jsonResultDO.setInfo("嘿币扣除失败");
				jsonResultDO.setStatus(JsonResultDO.JSON_FAILED);
				mav.addObject("JSON_DATA", jsonResultDO);
			}
		}else{
			jsonResultDO.setInfo("嘿币不足");
			jsonResultDO.setStatus(JsonResultDO.JSON_FAILED);
			mav.addObject("JSON_DATA", jsonResultDO);
		}
		need.setId(id);
		need.setStatus(2);
		need.setwSupplierId(supplierId);
		need.setwSupplierName(supplierDO.getwSName());
		need.setwSupplierTel(supplierDO.getwSTelephone());
		need.setModifiAuthor(supplierDO.getwSName());
		ResultDO resultNDO = needService.confirm(need);
		if(resultNDO.isSuccess()) {
			jsonResultDO.setInfo("需求抢单成功！");
			jsonResultDO.setStatus(JsonResultDO.JSON_SUCCESS);
			mav.addObject("JSON_DATA", jsonResultDO);
		} else {
			jsonResultDO.setInfo("需求抢单失败");
			jsonResultDO.setStatus(JsonResultDO.JSON_FAILED);
			mav.addObject("JSON_DATA", jsonResultDO);
		}

		return mav;
	}
	
	@RequestMapping(value = "/cancel/{id}.json", method = RequestMethod.GET)
	public ModelAndView needCancel(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		NeedDO needDO = new NeedDO();
		needDO.setId(id);
		needDO.setStatus(4);
		String memberMobile = (String) request.getSession().getAttribute("MEMBER_MOBILE");
		needDO.setModifiAuthor(memberMobile);
		ResultDO resultDO = needService.modify(needDO);
		System.out.println(resultDO.isSuccess());
		if(resultDO.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	
	@RequestMapping(value = "/confirm/{id}.json", method = RequestMethod.GET)
	public ModelAndView confirm(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		NeedDO needDO = new NeedDO();
		needDO.setId(id);
		needDO.setStatus(3);
		String memberMobile = (String) request.getSession().getAttribute("MEMBER_MOBILE");
		needDO.setModifiAuthor(memberMobile);
		ResultDO resultDO = needService.modify(needDO);
		
		if(resultDO.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	/**
	 * 删除订单
	 * @param mav
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/del/{id}.json", method = RequestMethod.GET)
	public ModelAndView del(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		ResultDO result = needService.remove(id);
		if(result.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	
	@RequestMapping(value = "/userNeeds/{status}/{pageNo}.html", method = RequestMethod.GET)
	public ModelAndView getUserNeeds(ModelAndView mav,
			@PathVariable(value="status") Integer status,
			@PathVariable(value="pageNo") Integer pageNo,
			HttpServletRequest request) {
		Cookie cookie = getCookieByName(request, "MEMBER_ID");	
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		}
		Integer memberId = Integer.parseInt(cookie.getValue());
		NeedQuery query = new NeedQuery();
		if(status != 0) {
			query.setStatus(status);
		}
		query.setMemberId(memberId);
		query.setPage(true);
		query.setPageNO(pageNo);
		query.setPageRows(1000);
		ResultDO result = needService.list(query);
		if(result.isSuccess()) {
			PageBeanUtil pageBean = new PageBeanUtil();
			long count = (Long) result.getModel(ResultSupport.SECOND_MODEL_KEY);
			pageBean.setCurrentPage(pageNo);
			pageBean.setPageSize(1000);
			pageBean.setRecordCount(count);
			pageBean.setPageCount(count);
			pageBean.setPages(pageNo);
			
			mav.addObject("NEED_LIST", result.getModel(ResultSupport.FIRST_MODEL_KEY));	
			mav.setViewName("need/userNeeds");
		} else {
			mav.setViewName("error");
		}
		
		return mav;
	}
	
	@RequestMapping(value = "/getNeed/{orderId}.json", method = RequestMethod.GET)
	public ModelAndView getNeedFromOrderId(ModelAndView mav,
			@PathVariable(value="orderId") Integer orderId,
			HttpServletRequest request) {
				
			ResultDO result = needService.getByOrderId(orderId);
			if(result.isSuccess()) {
				mav.addObject("JSON_DATA", result.getModel(ResultSupport.FIRST_MODEL_KEY));
			}else{
				mav.setViewName("error");
			}
		return mav;
	}
	
	@RequestMapping(value = "/findNeedById/{id}.json", method = RequestMethod.GET)
	public ModelAndView getNeedById(ModelAndView mav,
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		JsonResultDO jsonResultDO = new JsonResultSupport();
		ResultDO result = null;
		NeedDO needDo=null;
		List<NeedDO> list=new ArrayList<NeedDO>();
		SupplierQuery squery = new SupplierQuery();
		result = suppliersService.list(squery);
		List<SupplierDO> slist = (List<SupplierDO>) result.getModel(ResultSupport.FIRST_MODEL_KEY);
		String html = "<select id=\"supplierId\">";
		for(SupplierDO supplier : slist) {
			html += "<option value=\"" + supplier.getId() + "\">" + supplier.getwSName() + "</option>"; 
		}
		html += "</select>";
		System.out.println(html);
		if(result.isSuccess()) {
			result = needService.get(id);
			needDo=(NeedDO) result.getModel(ResultSupport.FIRST_MODEL_KEY);
			list.add(needDo);
			jsonResultDO.setInfo(html);
			jsonResultDO.setList(list);
			jsonResultDO.setStatus(JsonResultDO.JSON_SUCCESS);
			mav.addObject("JSON_DATA", jsonResultDO);
		} else {
			jsonResultDO.setStatus(JsonResultDO.JSON_FAILED);
			mav.addObject("JSON_DATA", jsonResultDO);
		}
		return mav;
	}
	
	@RequestMapping(value = "/getNeeds/{status}/{pageNo}.json", method = RequestMethod.GET)
	public ModelAndView getNeeds(ModelAndView mav,
			@PathVariable(value="status") Integer status,
			@PathVariable(value="pageNo") Integer pageNo,
			HttpServletRequest request) {
		NeedQuery query = new NeedQuery();
		query.setStatus(status);
		query.setPage(true);
		query.setPageNO(pageNo);
		query.setPageRows(1000);
		ResultDO result = needService.list(query);
		if(result.isSuccess()) {
			PageBeanUtil pageBean = new PageBeanUtil();
			long count = (Long) result.getModel(ResultSupport.SECOND_MODEL_KEY);
			pageBean.setCurrentPage(pageNo);
			pageBean.setPageSize(1000);
			pageBean.setRecordCount(count);
			pageBean.setPageCount(count);
			pageBean.setPages(pageNo);
			pageBean.setDataList((List<Object>) result.getModel(ResultSupport.FIRST_MODEL_KEY));
			mav.addObject("PAGE_BEAN", pageBean);
		} else {
			mav.setViewName("error");
		}
		
		return mav;
	}
	
	@RequestMapping(value = "/waitNeedList/{pageNo}.html", method = RequestMethod.GET)
	public ModelAndView waitNeedList(ModelAndView mav,
			@PathVariable(value="pageNo") Integer pageNo,
			HttpServletRequest request) {
		
		Integer supplierId = (Integer) request.getSession().getAttribute("MANAGER_SUPPLIER_ID");
		
		if(supplierId == null) {
			return new ModelAndView("redirect:/manager/login.html");
		}
		ResultDO sresultDO=suppliersService.get(supplierId);
		if(sresultDO.isSuccess()) {
			SupplierDO supplierDO=(SupplierDO) sresultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			int num=0;
			if(supplierDO.getwSMoney()!=null){
				num=supplierDO.getwSMoney();
			}
			mav.addObject("suMoney",num);
		}else {
			mav.setViewName("error");
			return mav;
		}
		
		NeedQuery query = new NeedQuery();
		query.setPage(true);
		query.setPageNO(pageNo);
		query.setPageRows(10);
		
		//标记
		int flags=0;
		String flag=request.getParameter("flag");
		if(flag!=null && !("".equals(flag))){
			flags=Integer.parseInt(flag);
			if(flags==1){
				//查询供应商
				query.setSupplierId(supplierId);
			}
		}
		
		//检索时间查询
		String start=request.getParameter("starts");
		String ends=request.getParameter("ends");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(start!=null && !("".equals(start))){
			Date date=null;
			try {
				date = sdf.parse(start+" 00:00:00");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			query.setStartDate(date);
		}
		
		if(ends!=null && !("".equals(ends))){
			Date ends2=null;
			try {
				ends2 = sdf.parse(ends+" 23:59:59");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			query.setEndDate(ends2);
		}
		
		ResultDO resultDO = needService.waitList(query);	
		
		if(resultDO.isSuccess()) {
			List<NeedDO> list = (List<NeedDO>) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			PageBeanUtil pageBean = new PageBeanUtil();
			long count = (Long) resultDO.getModel(ResultSupport.SECOND_MODEL_KEY);
			pageBean.setCurrentPage(pageNo);
			pageBean.setPageSize(query.getPageRows());
			pageBean.setRecordCount(count);
			pageBean.setPageCount(count);
			pageBean.setPages(pageNo);
			pageBean.setDataList((List<Object>) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY));
			mav.addObject("PAGE_BEAN", pageBean);
		} else {
			mav.setViewName("error");
			return mav;
		}
		
		if(flags==1){
			mav.setViewName("manager2/order/needList2");
		}else{
			mav.setViewName("manager2/order/needList");
		}
		return mav;
	}
	
	/**
	 * 成功和取消
	 * @param mav
	 * @param id
	 * @param status
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/changeStatus/{id}/{status}.json", method = RequestMethod.GET)
	public ModelAndView changeStatus(ModelAndView mav,
			@PathVariable(value="id") Integer id,
			@PathVariable(value="status") Integer status,
			HttpServletRequest request) {
		JsonResultDO jsonResultDO = new JsonResultSupport();
	
		NeedDO needDO= new NeedDO();
		needDO.setId(id);
		needDO.setStatus(status);
		//取消
		if(status!=null && status==1){
			needDO.setwSupplierId(null);
		}
		ResultDO result = needService.modify(needDO);
		if(result.isSuccess()) {
			jsonResultDO.setInfo("操作成功!");
			jsonResultDO.setStatus(JsonResultDO.JSON_SUCCESS);
			mav.addObject("JSON_DATA", jsonResultDO);
		} else {
			jsonResultDO.setInfo("操作失败!");
			jsonResultDO.setStatus(JsonResultDO.JSON_FAILED);
			mav.addObject("JSON_DATA", jsonResultDO);
		}
		
		return mav;
	}
	
}

